<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      class ProxySandbox {
        constructor() {
          // 控制激活和失活
          this.running = false;
          const fakeWindow = Object.create(null);
          this.proxy = new Proxy(fakeWindow, {
            get: (target, key) => {
              // 获取的时候，先从 fakeWindow 上取值，如果取不到，再从 window 上取值
              return key in target ? target[key] : window[key];
            },
            set: (target, key, value) => {
              if (this.running) {
                // 激活才去设置
                target[key] = value;
              }
              return true;
            },
          });
        }
        active() {
          if (!this.running) this.running = true;
        }
        inactive() {
          this.running = false;
        }
      }

      const sandbox1 = new ProxySandbox();
      const sandbox2 = new ProxySandbox();
      sandbox1.active();
      sandbox2.active();
      // 修改不会影响window，不用去还原window
      sandbox1.proxy.a = 100;
      sandbox2.proxy.a = 200;
      console.log(sandbox1.proxy.a, sandbox2.proxy.a); // 100 200
      sandbox1.inactive();
      sandbox2.inactive();
      sandbox1.proxy.a = 200;
      sandbox2.proxy.a = 400;
      console.log(sandbox1.proxy.a, sandbox2.proxy.a); // 100 200

      (function (window) {
        console.log(window.a); // 100
      })(sandbox1.proxy);
    </script>
  </body>
</html>
